package com.meixiang.dialog;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.meixiang.R;
import com.meixiang.activity.account.manager.VerifyPhoneNumberPayOffActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 交易密码键盘
 */
public class TradersPasswordtKeyDialog extends Dialog implements OnClickListener, OnItemClickListener {
    private ImageView ivClose;
    private TextView tvMoneys;
    private TextView tvTitle;
    private TextView tvForgetPasword;//忘记密码
    //显示6位密码的view
    private GridView mKeyShowGridGridView;
    //忘记密码的view
    //键盘view
    private GridView mKeyInputGridGridView;
    //当前activity
    private Activity activity;
    //当前布局
    private View view;
    //键盘适配器
    private KeyGridAdapter keyGridAdapter;
    private String[] keyList = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "", "0", ""};
    //    private int[] keyList={R.drawable.key_one,R.drawable.key_two,
//            R.drawable.key_three,R.drawable.key_four,R.drawable.key_five,
//            R.drawable.key_six,R.drawable.keyboard_seven,R.drawable.keyboard_eight,
//            R.drawable.keyboard_nine,R.drawable.keyboard_space,R.drawable.key_zero,R.drawable.key_del};
    private List<String> showList = new ArrayList<>();
    private ShowGridAdapter adapter;
    private String password = "";
    private OnCustomDialogListener listener;
    private Display d;
    private Animation animation;
    private String title;
    private String money;
    /**
     * 唯一构造方法
     *
     * @param activity
     * @param listener 回调接口,可获取当前dialog与输入的交易密码.
     */
    public TradersPasswordtKeyDialog(Activity activity,String title,String money, OnCustomDialogListener listener) {
        super(activity);
        this.activity = activity;
        this.title=title;
        this.money=money;
        this.listener = listener;
        if (!isShowing()){
            show();
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        view = LayoutInflater.from(activity).inflate(R.layout.trader_password_key, null);
        setContentView(view);
        initDialog();
        initView();
        Event();
    }

    private void initDialog() {
        //设置不可点击外部消失
        setCancelable(false);
        //设置风格为无
        getWindow().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(activity, R.color.transparent)));
        /*
         * 将对话框的大小按屏幕大小的百分比设置
         */
        WindowManager m = activity.getWindowManager();
        d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = getWindow().getAttributes(); // 获取对话框当前的参数值
        p.height = WindowManager.LayoutParams.WRAP_CONTENT; // 高度设置为布局高度
        p.width = WindowManager.LayoutParams.MATCH_PARENT;
         // 宽度设置为屏幕的全宽
        getWindow().setAttributes(p);
        //设置为底部
        getWindow().setGravity(Gravity.BOTTOM);
        //
        animation = AnimationUtils.loadAnimation(activity, R.anim.dialog_close);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                dismiss();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    private void initView() {
        tvTitle= (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(title);
        tvMoneys= (TextView) findViewById(R.id.tv_moneys);
        tvMoneys.setText("¥ "+Tool.toDivAccount2(money));
        mKeyShowGridGridView = (GridView) findViewById(R.id.key_show_grid);
        mKeyInputGridGridView = (GridView) findViewById(R.id.key_input_grid);
        //tvWithdrawMoneys=(TextView)findViewById(R.id.tv_wait_moenys);
        tvForgetPasword = (TextView) findViewById(R.id.tv_forget_pasword);//忘记密码
        ivClose = (ImageView) findViewById(R.id.iv_close);
        keyGridAdapter = new KeyGridAdapter(keyList, activity);
        mKeyInputGridGridView.setAdapter(keyGridAdapter);
        mKeyInputGridGridView.setOnItemClickListener(this);
        for (int i = 0; i < 6; i++) {
            showList.add("");
        }
        adapter = new ShowGridAdapter(activity);
        mKeyShowGridGridView.setAdapter(adapter);
        adapter.UpdateData(showList);
    }

    private void Event() {
        ivClose.setOnClickListener(this);
        tvForgetPasword.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.tv_forget_pasword:
                 activity.startActivity(new Intent(activity,VerifyPhoneNumberPayOffActivity.class));
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            view.startAnimation(animation);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //点击数字，添加到集合
        if (showList.get(5).equals("") && position != 9 && position != 11) {
            for (int i = 0; i < showList.size(); i++) {
                if (showList.get(i).equals("")) {
                    showList.set(i, keyList[position]);
                    break;
                }
            }
        } else {
            password = "";
        }
        //点击X，删除后面一位
        if (position == 11) {
            for (int i = showList.size() - 1; i >= 0; i--) {
                if (!showList.get(i).equals("")) {
                    showList.set(i, "");
                    break;
                }
            }
            password = "";
        }
        //更新显示的密码
        adapter.UpdateData(showList);
        //如果输满6位，则调用回调方法
        if (!showList.get(5).equals("")) {
            for (int i = 0; i < showList.size(); i++) {
                password += showList.get(i);
            }
               listener.getPayPassWord(this, password);
        }
    }

    //定义回调事件，用于dialog的点击事件
    public interface OnCustomDialogListener {
        /**
         * 回调方法，可获取当前对象与输入的密码
         *
         * @param paymentKeyDialog
         * @param password
         */
        public void getPayPassWord(TradersPasswordtKeyDialog paymentKeyDialog, String password);
    }


    @Override
    public void dismiss() {
        super.dismiss();
        cancelPass();
    }



    /**
     * 清除密码
     */
    public void cancelPass() {
        password = "";
        for (int i = showList.size() - 1; i >= 0; i--) {
            if (!showList.get(i).equals("")) {
                showList.set(i, "");
            }
        }
        adapter.UpdateData(showList);
    }

    @Override
    protected void onStop() {
        dismiss();
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        view.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.dialog_start));
    }


    //适配器
    class ShowGridAdapter extends BaseAdapter {
        private List<String> showList = new ArrayList<>();
        private LayoutInflater inflater;

        public ShowGridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void UpdateData(List<String> showList) {
            this.showList = showList;
            notifyDataSetInvalidated();
        }

        @Override
        public int getCount() {
            return showList.size();
        }

        @Override
        public Object getItem(int position) {
            return showList.get(position);

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.payment_key_show_itme, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.viewright.setBackgroundResource(R.color.blue_btn_disable);
            viewHolder.viewright.getLayoutParams().width = DensityUtil.dip2px(activity, 1);
            viewHolder.viewtop.setVisibility(View.GONE);
            if (position == 5) {
                viewHolder.viewright.setVisibility(View.GONE);
            }
            if (showList.get(position).equals("")) {
                viewHolder.itemtxt.setText("");
            } else {
                viewHolder.itemtxt.setText("●");
            }
            return convertView;
        }
    }

    class KeyGridAdapter extends BaseAdapter {
        String[] keyList = new String[12];
        private LayoutInflater inflater;

        public KeyGridAdapter(String[] keyList, Context context) {
            this.keyList = keyList;
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return keyList.length;
        }

        @Override
        public Object getItem(int position) {
            return keyList[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.payment_key_itme, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (position == 2 || position == 5 || position == 8 || position == 11) {
                viewHolder.viewright.setVisibility(View.GONE);
            } else {
                viewHolder.viewright.setVisibility(View.VISIBLE);
            }
            if (position==11){
                Drawable drawable = ContextCompat.getDrawable(activity,R.drawable.key_del);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                viewHolder.itemtxt.setBackground(drawable);
                //viewHolder.itemtxt.setCompoundDrawables(drawable,null,null,null);
            }
            if (position==9){
                Drawable drawable = ContextCompat.getDrawable(activity,R.drawable.keyboard_space);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                viewHolder.itemtxt.setBackground(drawable);
                //nviewHolder.itemtxt.setCompoundDrawables(drawable,null,null,null);
                convertView.setClickable(false);
            }

            viewHolder.itemtxt.setText(keyList[position]);
            return convertView;
        }

    }

    public class ViewHolder {
        public final View viewtop;
        public final TextView itemtxt;
        public final View viewright;
        public final View root;

        public ViewHolder(View root) {
            viewtop = (View) root.findViewById(R.id.view_top);
            itemtxt = (TextView) root.findViewById(R.id.item_txt);
            viewright = (View) root.findViewById(R.id.view_right);
            this.root = root;
        }
    }
}
